#include "mcu.h"
#include "gpio.h"
#include "types.h"

void mcu_watchdog_disable()
{
    SET_BIT(PCA0MD, BIT_6, 0);
}
void mcu_watchdog_enable(UINT8 ms)
{
    //TODO
    DBG_ASSERT(FALSE);
}
void mcu_watchdog_feed()
{
    //TODO
    DBG_ASSERT(FALSE);
}

void mcu_change_sysclock(MCU_SYSCLK_LEVEL_T clk)
{
    switch(clk)
    {
    case MCU_SYSCLK_LEVEL_MIN:
        //TODO:add other configs
    case MCU_SYSCLK_LEVEL_MIDDLE:
        //TODO:add other configs
    case MCU_SYSCLK_LEVEL_MAX:
      {
          OSCICN = 0x87;                      // configure internal oscillator for
                                              // 24.5MHz
          RSTSRC = 0x04;                      // enable missing clock detector
          break;
      }
    }
}

void mcu_ports_init(void)
{
    P0MDOUT = 0xFF;				// Enable UTX and SPI0(MO NSS SCK) as push-pull output
	P1MDOUT = 0xFF;				// P1 is push-pull
	P2MDOUT = 0xFF;				// P2 is push-pull

	P0 = 0xFF;						// Set latch to '1'
	P1 = 0xFF;
	P2 = 0xFF;

	SET_BIT(XBR0, BIT_0, 1);			// Enable UART on P0.4(TX) and P0.5(RX)
	SET_BIT(XBR1, BIT_6, 1);			// Enable crossbar and enable weak pull-ups
}

void mcu_interrupt_init(void)
{
	/* mask all interrupt */
	IE = 0;
	EIE1 = 0;

	/* set interrupt priority: ALL to LOW */
	IP = 0;
	EIP1 = 0;
}

void mcu_init(void)
{
    mcu_watchdog_disable();
    mcu_ports_init();
    mcu_interrupt_init();

    //gear up to 24.5MHz
    mcu_change_sysclock(MCU_SYSCLK_LEVEL_MAX);

    // enable the mcu interrupts
    MCU_INTERRUPT_ON;
}

